using System;
using System.Configuration;

namespace FormsGenerator.DataAccess
{
	/// <summary>
	/// Singleton class for getting the db-interface connection.
	/// </summary>
	public sealed class DBFactory
	{
		private IDBHandler _dbInstance;
		class ThreadSafeSingelton
		{
		    internal static readonly DBFactory Instance = new DBFactory();
		}

		public static DBFactory Instance
		{
			get { return ThreadSafeSingelton.Instance; }
		}

		private DBFactory()
		{	
		}

		public IDBHandler DBHandlerInstance()
		{
			if (IsInterfaceConfigured())
			{
				IDBHandler handler = GetInstance();
				return handler;
			}
		    Exception e = new Exception("Failed to create an implementation for interface IDBHandler",null);
		    throw(e);
		}

		private static bool IsInterfaceConfigured()
		{
			//TODO: have to implement this! 
			return true;
		}

		private IDBHandler GetInstance()
		{
			//TODO: have to implement this correctly!
			//it is supposed to get the assembly and class that implements the dbhandler and crate an instance according to this.
			if(_dbInstance == null)
			{
                object selectedClass = ConfigurationManager.GetSection("DBHandler");
				string interfaceImplementation = selectedClass.ToString();
				Type type = Type.GetType(interfaceImplementation);
				object oInstance = Activator.CreateInstance(type);
				_dbInstance = (IDBHandler)oInstance;				
			}

			return _dbInstance;
		}
	}
}
